<template>
  <div class="app-container">
    <div class="search-container">
      <el-input v-model="keywords" class="search-input" placeholder="请输入角色名" :clearable="true" @keyup.enter.native="getList({pageNo:1})" />
      <el-button type="primary" size="small" icon="el-icon-search" @click="getList({pageNo:1})">搜索</el-button>
    </div>
    <div class="function-buttons">
      <el-button v-hasPermission="['sys_role_add']" type="primary" size="small" icon="el-icon-edit" @click="save">新增</el-button>
    </div>
    <div>
      <el-table v-loading="listLoading" :data="list" border fit highlight-current-row>
        <el-table-column align="center" label="序号" width="120px" type="index" />

        <el-table-column align="center" label="角色名">
          <template slot-scope="scope">
            <span>{{ scope.row.name }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="描 述">
          <template slot-scope="scope">
            <span>{{ scope.row.description }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="添加时间">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button v-hasPermission="['sys_role_edit']" type="text" @click="update(scope.row)">编辑</el-button>
            <el-button v-hasPermission="['sys_role_addResource']" type="text" @click="assignmentShow(scope.row)">分配权限</el-button>
            <el-popconfirm
              title="确认删除吗？"
              confirm-button-type="warning"
              confirm-button-text="删除"
              class="customConfirm"
              @onConfirm="del(scope.row.id)"
            >
              <el-button slot="reference" v-hasPermission="['sys_role_delete']" type="text">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageSize" @pagination="pageChange" />
    </div>
    <div>
      <el-dialog title="更新" :visible.sync="saveForm.visible">
        <el-form ref="saveForm" :model="saveForm.props" :rules="saveForm.rules" label-width="80px">
          <el-form-item label="角色名" prop="name">
            <el-input v-model="saveForm.props.name" />
          </el-form-item>
          <el-form-item label="描 述" prop="description">
            <el-input v-model="saveForm.props.description" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel('saveForm')">取 消</el-button>
          <el-button type="primary" @click="doSave">确 定</el-button>
        </div>
      </el-dialog>
      <el-dialog title="分配权限" :visible.sync="assignment.visible">
        <el-form ref="saveForm" label-width="80px" style="max-height: 500px;overflow: auto">
          <el-tree
            ref="tree"
            :data="assignment.list"
            show-checkbox
            node-key="id"
            default-expand-all
            :props="assignment.defaultProps"
            :default-checked-keys="assignment.roleResourceIdList"
            @check="handleClick"
          />
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="assignment.visible = false">取 消</el-button>
          <el-button type="primary" :disabled="btnSubmitDisabled" @click="assignmentSave">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import request from '@/utils/request'
export default {
  name: 'TopicList',
  components: { Pagination },
  data() {
    return {
      btnSubmitDisabled: false,
      visible: false,
      list: null,
      keywords: null,
      total: 0,
      listLoading: true,
      listQuery: {
        pageNo: 1,
        pageSize: 10
      },
      saveForm: {
        visible: false,
        props: {
          id: '',
          name: '',
          description: '',
          createTime: ''
        },
        rules: {
          name: this.formRules({
            required: true,
            min: 1,
            max: 100
          }),
          description: this.formRules({
            required: true,
            min: 1,
            max: 100
          }),
          postImgPath: this.formRules({
            required: true
          }),
          title: this.formRules({
            required: true,
            min: 1,
            max: 100
          }),
          announcement: this.formRules({
            required: true,
            min: 1,
            max: 200
          }),
          validDateRange: this.formRules({
            type: 'array',
            required: true
          }),
          contentPath: this.formRules({
            required: true
          })
        }
      },
      assignment: {
        visible: false,
        list: [],
        resourcesIds: [],
        roleResourceIdList: [],
        defaultProps: {
          children: 'children',
          label: 'label'
        }
      }
    }
  },
  created() {
    this.getList({
      pageNo: this.listQuery.pageNo
    })
  },
  methods: {
    pageChange(page) {
      this.getList({
        pageNo: page.page
      })
    },
    getList(params) {
      this.listLoading = true;
      const pageNo = params.pageNo ? params.pageNo : this.listQuery.pageNo;
      request({
        url: '/system/sysRole/getPageList',
        method: 'post',
        data: {
          name: this.keywords,
          pageNo: pageNo,
          pageSize: this.listQuery.pageSize
        }
      }).then(res => {
        const data = res.data;
        this.list = data.rows;
        this.total = data.total;
        if (data.pageCount < pageNo) {
          this.listQuery.pageNo = data.pageCount;
        }
        this.listLoading = false
      })
    },
    save() {
      this.saveForm.props = {
        id: '',
        name: '',
        description: '',
        createTime: ''
      };
      this.saveForm.visible = true
    },
    update(data) {
      this.saveForm.props = {
        id: data.id,
        name: data.name,
        description: data.description
      };
      this.saveForm.visible = true
    },
    del(id) {
      const _this = this;
      request({
        url: '/system/sysRole/delete',
        method: 'post',
        params: {
          id: id
        }
      }).then(res => {
        this.$message.success('删除成功')
        this.getList({
          pageNo: (this.list.length === 1 && _this.listQuery.pageNo !== 1) ? _this.listQuery.pageNo - 1 : _this.listQuery.pageNo
        });
      })
    },
    doSave() {
      const _this = this;
      this.$refs.saveForm.validate(valid => {
        if (!valid) {
          return;
        }
        request({
          url: '/system/sysRole/save',
          method: 'post',
          data: {
            id: _this.saveForm.props.id,
            description: _this.saveForm.props.description,
            name: _this.saveForm.props.name
          }
        }).then(res => {
          _this.$message.success('保存成功');
          _this.getList({
            pageNo: 1
          });
          _this.saveForm.visible = false;
        })
      });
    },
    postImgUploadSuccess(res, file) {
      if (res.code !== 200) {
        this.$message.error('上传失败: ' + res.message);
        return;
      }
      this.saveForm.props.postImgPath = res.data.url;
    },
    // 取消
    cancel(formName) {
      this.$refs[formName].clearValidate();
      this.$refs[formName].resetFields();
      this.saveForm.visible = false;
    },
    assignmentShow(data) {
      this.saveForm.props.id = data.id;
      this.assignment.resourcesIds = [];
      this.assignment.roleResourceIdList = [];
      this.getRoleResourceIdList(data.id);
    },
    getResourceTree(data) {
      var _this = this;
      request({
        method: 'get',
        url: `/system/sysResource/getResourceTree`
      }).then(res => {
        _this.assignment.list = res.data;
        if (data != null) {
          _this.$nextTick(function() {
            _this.$refs.tree.setCheckedKeys(data);
          })
        }
        this.assignment.visible = true
      })
    },
    getRoleResourceIdList(roleId) {
      var _this = this;
      request({
        url: `/system/sysRoleResource/getResourcesIdListByRoleId`,
        method: 'post',
        data: {
          roleId: roleId
        }
      }).then(res => {
        _this.assignment.roleResourceIdList = res.data.checkedTreeList;
        _this.assignment.resourcesIds = res.data.treeList;
        _this.getResourceTree(_this.assignment.roleResourceIdList)
      })
    },
    handleClick(nodeObj, selectedObj) {
      this.assignment.resourcesIds = selectedObj.checkedKeys.concat(selectedObj.halfCheckedKeys);
    },
    assignmentSave() {
      const _this = this;
      this.btnSubmitDisabled = true;
      request({
        url: '/system/sysRoleResource/addResource',
        method: 'post',
        data: {
          resourcesIds: this.assignment.resourcesIds,
          roleId: _this.saveForm.props.id
        }
      }).then(res => {
        _this.$message.success('保存成功');
        _this.assignment.visible = false;
        _this.btnSubmitDisabled = false;
      }).catch(e => {
        _this.btnSubmitDisabled = false;
      })
    }

  }
}
</script>

<style>
  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .el-upload:hover {
    border-color: #409EFF;
  }
  .upload-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .post-image {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
